package com.hakim.wfb.schedule.dao

import com.alibaba.fastjson.JSONObject
import com.hakim.wfb.schedule.utils.SqlUtil
import groovy.sql.Sql
import org.apache.commons.lang3.StringUtils
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import org.slf4j.LoggerFactory

/**
 */
class scheduleDao {

    static def logger = LoggerFactory.getLogger("scheduleDao")

    static Sql scheduleSql = SqlUtil.scheduleSql

    static Map<String, Object> getJobDetailByCode(String jobCode) {
        def jobList = scheduleSql.rows("select * from tb_job_config  WHERE jobCode = ?", [jobCode])
        if (jobList && !jobList.empty) {
            def job = jobList.get(0)
            if (job && job.status == 1) {
                Map<String, Object> jobDetail = JSONObject.parse(job.jobDetail)
                if (jobDetail) {
                    return jobDetail
                }
            } else {
                logger.info("任务不存在或失效，不予执行{}", JSONObject.toJSONString(job))
            }
        }
    }

    static List<String> getJobCodesFromDB(String status) {
        def sql = "select jobCode from tb_job_config"
        if (StringUtils.isNotBlank(status)) {
            sql += " WHERE status = ${status}"
        }
        def jobList = scheduleSql.rows(sql)
        def jobs = []
        jobList.each {
            jobs.add(it.get("jobCode"))
        }
        jobs
    }

    static boolean addJobLog(String jobCode, Long totalNum, Long errorNum) {
        return scheduleSql.execute("replace into tb_job_execute_log(jobCode,totalNum,successNum,errorNum,recordTime) values(?,?,?,?,?)",
                [jobCode, totalNum, totalNum - errorNum, errorNum, new Date()])
    }

    static String getCronByCode(String jobCode) {
        def jobList = scheduleSql.rows("select cron from tb_job_config WHERE jobCode = ? AND status = 1", [jobCode])
        if (jobList && !jobList.empty) {
            def job = jobList.get(0)
            if (job) {
                return job.get("cron")
            }
        }
    }

//    static String getActivityFieldByTime(Date updatedDate, String code) {
//        def activityIdsSql = "SELECT ${code} code FROM tb_activity WHERE ? BETWEEN startTime AND endTime"
//        def activityIds = ""
//        List retList = scheduleSql.rows(activityIdsSql, [updatedDate])
//        if (retList) {
//            for (Map retMap : retList) {
//                activityIds += "${retMap.code}|"
//            }
//            activityIds = activityIds.substring(0, activityIds.length() - 1)
//        }
//        return activityIds
//    }

    static Date[] getMinusAndPlusDays(String jobCode) {
        Map<String, Object> jobDetail = getJobDetailByCode(jobCode)
        Date defaultStartTime = DateTime.now().minusDays(1).toDate()
        Date defaultEndTime = DateTime.now().plusDays(1).toDate()
        if (!jobDetail) {
            return [defaultStartTime, defaultEndTime]
        }
        //是否为时间区
        if (jobDetail.isInterval == 1) {
            Date startTime = DateTimeFormat.forPattern("yyyy-MM-dd HH").parseDateTime(jobDetail.startTime).toDate()
            Date endTime = DateTimeFormat.forPattern("yyyy-MM-dd HH").parseDateTime(jobDetail.endTime).toDate()
            return [startTime, endTime]
        }
        //存在时间间隔值
        if (jobDetail.intervalDays > 0) {
            Date startTime = DateTime.now().minusDays(jobDetail.intervalDays as int).toDate()
            Date endTime = DateTime.now().plusDays(1).toDate()
            return [startTime, endTime]
        }
        return [defaultStartTime, defaultEndTime]
    }

    public static void main(String[] args) {
        boolean retBoo = scheduleDao.addJobLog("dycChannelSyncJob", 100, 2)
        println retBoo
    }
}
